package com.hancheng.commoncloud.framework.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
@Slf4j
public class ValidatorUtils {

    private static MessageSource messageSource;

    @Autowired
    public ValidatorUtils(MessageSource messageSource) {
        ValidatorUtils.messageSource = messageSource;
    }

    public static String message(String code, Object... args) {
        if (StrUtil.isBlank(code)) {
            return "";
        }
        // 从请求上下文获取语言环境
        Locale locale = LocaleContextHolder.getLocale();

        try {
            return messageSource.getMessage(code, args, locale);
        } catch (NoSuchMessageException ex) {
            log.warn("国际化资源缺失，code：{}，locale：{}", code, locale);
            return code;
        }
    }
}
